package app.controllers.system;

import app.models.system.Resource;
import app.models.system.Role;
import app.models.system.RoleResource;
import com.ifonly.activerecord.ActiveRecordFactory;
import com.ifonly.activerecord.Record;
import com.ifonly.common.ApiMessage;
import com.ifonly.common.ztree.simple.SimpleZNode;
import com.ifonly.mvc.ActionKey;
import com.ifonly.mvc.Controller;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ifonly
 * @version 1.0 2016-01-21 13:18
 * @since JDK 1.6
 */
public class RoleController extends Controller {
    private RoleResource dao = ActiveRecordFactory.getActiveRecord(RoleResource.class);

    @ActionKey("")
    public void index() {
        render("index");
    }

    public void dt() {
        renderDataTables(Role.class);
    }

    public void item() {
        int id = getInt(0);
        Role role;
        if (id == 0) {
            role = new Role();
        } else {
            role = Role.findByPrimaryKey(Role.class, id);
        }
        setAttr("role", role);
        render("item");
    }

    public void resources() {
        int roleId = getInt(0, 0);
        List<Record> records = dao.findResourcesWithRole(roleId);
        List<SimpleZNode<Integer, Resource>> zNodes = new ArrayList<SimpleZNode<Integer, Resource>>();
        SimpleZNode<Integer, Resource> e = SimpleZNode.create(0, null, "全部资源", null);
        zNodes.add(e);

        StringBuilder sb = new StringBuilder();

        for (Record record : records) {
            SimpleZNode<Integer, Resource> zNode = new SimpleZNode<Integer, Resource>();
            zNode.setId(record.getInt("id"));
            zNode.setName(record.getString("name"));
            zNode.setPid(record.getInteger("pid"));
            zNode.setOpen(true);
            sb.append(record.getInt("id")).append(",");
            if (record.get("resourceId") != null) {
                zNode.setChecked(true);
                e.setChecked(true);
            }
            zNodes.add(zNode);
        }

        renderJson(ApiMessage.success(sb.toString(), zNodes));
    }

    public void save() {
        Role role = getModel(Role.class, "role");
        String resourceIds = getParam("resourceIds");
        dao.saveRoleWithResource(role, resourceIds);
        redirect("");
    }

    public void delete() {
        int roleId = getInt(0, 0);
        if (roleId == 0) {
            renderJson(ApiMessage.failed("参数错误"));
            return;
        }
        dao.deleteRoleWithResource(roleId);
        renderJson(ApiMessage.success());
    }

}
